//
//  CZOAuth.swift
//  WeiBO28
//
//  Created by 飞奔的羊 on 16/5/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

//新浪微博的 appkey
  let WeiboAppKey = "1690635982"
//授权回调页
let WeiBoUrl = "http://www.baidu.com"

let WeiboAppSecret = "99ff60c349159f2144490f9b1bb985b3"

class CZOAuth: UIViewController {

    
    private lazy var weiView: UIWebView = UIWebView()
    
    override func loadView() {
		
		
		weiView.delegate = self
		
		
        view = weiView
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavUI()
        
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiBoUrl)"
        
        let request = NSURLRequest(URL: NSURL(string: url)!)
        
        weiView.loadRequest(request)
        
        
        
        
    }
    
    private func setupNavUI() {
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 15, target: self, action: #selector(CZOAuth.cancle))
    
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动登录", fontSize: 15, target: self, action: #selector(CZOAuth.auto))
        navigationItem.title = "微博登录"
    }
    
    // MARK: ------点击事件------
    @objc private func cancle() {
    dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    
    @objc private func auto() {
//        weiView
        weiView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '452239611@qq.com'; document.getElementById('passwd').value = 'zy__++7222948'")
        
    }

}



extension CZOAuth: UIWebViewDelegate {
//将要加载函数请求的方法
	func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
		
//		print(request.URL?.absoluteString)
		
		guard let url = request.URL else {
		
			return false
		}
		
		//取反就不是我们想要关心的 url
		if !url.absoluteString.hasPrefix(WeiBoUrl) {
		
		return true
		
		}
		//代码执行到此.是不是我们需要关心的 url
		//query 就是我们请求地址里面的参数
//		print( url.query )
		
		//以我们 code 打头我们才去截取
		if let  query = url.query where query.hasPrefix("code=") {
		
			let code = query.substringFromIndex("code=".endIndex)
			CZUserAccountViewModel.shareUserAccount.requestAccessToken(code, complete: { (isSuccess) in
				
				if isSuccess {
				
					print("登录成功")
					//需要当前控制器 dismiss 完成以后才发送通知切换视图控制器
					self.dismissViewControllerAnimated(false, completion: { 
						NSNotificationCenter.defaultCenter().postNotificationName(SwithRootVCNotification, object: self)
					})
					
					
				} else {
				
				SVProgressHUD.showErrorWithStatus("登录失败")
				}
				
			})
		
		} else {
		//取消回调页
			dismissViewControllerAnimated(true, completion: nil)
		
		
		}
		print("000" + url.absoluteString)
		
		
		return false
		
	}
	func webViewDidStartLoad(webView: UIWebView) {
		SVProgressHUD.show()
		
		
	}
	func webViewDidFinishLoad(webView: UIWebView) {
		SVProgressHUD.dismiss()
	}
	
	func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
		SVProgressHUD.dismiss()
	}
	

}

func test() {
	//
	//	private func requestAccessToken(code: String)
	//	{
	//	let url = "https://api.weibo.com/oauth2/access_token"
	//		let params = [
	//		"client_id": WeiboAppKey,
	//			"client_secret": WeiboAppSecret,
	//		"grant_type": "authorization_code",
	//			"code": code,
	//			"redirect_uri": WeiBoUrl
	//		]
	//		let sessionManger = AFHTTPSessionManager()
	//		sessionManger.responseSerializer.acceptableContentTypes?.insert("text/plain")
	//		sessionManger.POST(url, parameters: params, progress: nil, success: { (_, response) in
	//
	//			guard let dic = response as? [String: AnyObject] else {
	//
	//				print("非正确格式")
	//				return
	//			}
	//			//执行到这是字典
	//			let userAccount = CZUserAcount(dic: dic)
	//
	//
	//			}) { (_, error) in
	//
	//
	//
	//		}
	//
	//
	//
	//	}
	//
	//	private func requestUserInfo(userAccount: CZUserAcount) {
	//
	//		let url = "https://api.weibo.com/2/users/show.json"
	//
	//		let params = [
	//		"access_token": userAccount.access_token!,
	//			"uid":"\(userAccount.uid)"
	//
	//
	//		]
	//		let sessionManger = AFHTTPSessionManager()
	//		sessionManger.responseSerializer.acceptableContentTypes?.insert("text/plain")
	//		sessionManger.GET(url, parameters: params, progress: nil, success: { (_, response) in
	//
	//			guard let dic = response as? [String: AnyObject] else {
	//
	//				print("非正确格式")
	//				return
	//			}
	////			//执行到这是字典
	////			let userAccount = CZUserAcount(dic: dic)
	//
	//			userAccount.name = dic["name"] as? String
	//			userAccount.avatar_large = dic["avatar_large"] as? String
	//
	//		}) { (_, error) in
	//
	//
	//			
	//		}
	//	
	//	
	//	
	//	}
	//    
	//    
	//	
	//    
	//
}



